
var names = document.getElementsByTagName('h3');

function init() {
    var listener = new GamepadListener({}, false);

    listener.on('gamepad:connected', function (e) {
        // console.log('connected', e);
        var index = e.detail.gamepad.index,
            id = e.detail.gamepad.id;
        names[index].innerHTML = id;
    });

    listener.on('gamepad:disconnected', function (e) {
        var index = e.detail.index;
        names[index].innerHTML = 'gamepad has just been disconnected, press a button';
    });
//axis
    listener.on('gamepad:axis', function (e) {
        var index = e.detail.gamepad.index,
            axis = e.detail.axis,
            value = e.detail.value;
        console.log(`转动摇杆, ${index}, ${axis}, ${value}`)
        
        if(axis == 0 && value==1){
            s.dir(1,0);
        } else if(axis == 0 && value== -1){
            s.dir(-1,0);
        } else if(axis == 1 && value== 1){
            s.dir(0,1);
        } else if(axis == 1 && value== -1){
            s.dir(0,-1);
        }
    });
//buttons
    listener.on('gamepad:button', function (e) {
        var index = e.detail.gamepad.index,
            button = e.detail.index,
            pressed = e.detail.pressed ? 'pressed' : 'released',
            value = e.detail.value;
        console.log(`Button ${index}, ${button}, ${pressed}, ${value} pressed`)
    });
    listener.start();
}

window.addEventListener('load', init);